package cn.jobstart.common.http;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ningbohezhijun on 16/5/13.
 */
public class AuthPostJSON {

    private static final Logger log = LoggerFactory.getLogger(AuthPostJSON.class);

//    private static HttpClient httpClient;
//
//    static {
//        try {
//            httpClient = new SSLClient();
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.exit(1);
//        }
//    }

    public static <T> T authPostJSON(String url, String content, Class<T> returnType, int soTimeout, int conTimeout, String... headers) {
        try {

            return tryPostJson(url, content, returnType, soTimeout, conTimeout, headers);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static <T> T tryPostJson(String url, String content, Class<T> returnType, int soTimeout, int conTimeout, String... headers) throws Exception {


        HttpClient httpClient = HttpRequest.getHttpClient();

        HttpPost post = new HttpPost(url);
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, conTimeout);
        post.setParams(params);
        StringEntity body = new StringEntity(content, "utf-8");
        body.setContentType("Content-Type: application/json; charset=utf-8");
        post.setEntity(body);
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        return execute(httpClient, post, returnType, headers);


    }






    public static <T> T tryAuthPostJSON(String url, String content, Class<T> returnType, int soTimeout, int conTimeout, String... headers) {

        int tryCount = 3;

        while (tryCount-- > 0) {
            try {
                return tryPostJson(url, content, returnType, soTimeout, conTimeout, headers);
            } catch (Exception e) {

            }


        }

        return null;


    }


    public static <T> T execute(HttpClient httpClient, HttpUriRequest req, Class<T> returnType, String... headers) throws Exception {

        try {
            // 插入basic验证等基础逻辑
            for (int i = 0; i < headers.length; i += 2) {
                req.addHeader(headers[i], headers[i + 1]);
            }
            HttpResponse jres = httpClient.execute(req);

            HttpEntity ent = jres.getEntity();
            String content = ent != null ? EntityUtils.toString(ent, "UTF-8") : null;
            if (jres.getStatusLine().getStatusCode() >= 200
                    && jres.getStatusLine().getStatusCode() < 300) {
                if (returnType == String.class) {
                    return (T) content;
                }
                return JSON.parseObject(content, returnType);
            } else {
                log.warn("error response code={}", new Object[]{jres.getStatusLine().getStatusCode()});
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("request error,", e);
            throw e;
        }
        return null;
    }

}
